package xyz.jcat.dys.aweme.dubbo;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import xyz.jcat.common.exception.BusinessException;
import xyz.jcat.common.util.BusinessUtils;
import xyz.jcat.dys.aweme.api.IAwemeCommentDubboService;
import xyz.jcat.dys.aweme.api.dto.AwemeCommentAddDto;
import xyz.jcat.dys.aweme.domain.document.AwemeCommentDocument;
import xyz.jcat.dys.aweme.service.IAwemeCommentService;
import xyz.jcat.dys.aweme.service.IAwemeService;

@Slf4j
@DubboService
public class AwemeCommentDubboService implements IAwemeCommentDubboService {

    @Autowired
    private IAwemeCommentService awemeCommentService;
    @Autowired
    private IAwemeService awemeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAwemeComment(AwemeCommentAddDto awemeCommentAddDto) {
        //增加作品评论数
        boolean result = awemeService.updateComments(awemeCommentAddDto.getAwemeId(), 1L);
        if(!result) {
            return;
        }
        AwemeCommentDocument awemeCommentDocument = new AwemeCommentDocument();
        awemeCommentDocument.setUserId(awemeCommentAddDto.getUserId());
        awemeCommentDocument.setAwemeId(awemeCommentAddDto.getAwemeId());
        awemeCommentDocument.setContent(awemeCommentAddDto.getContent());
        awemeCommentDocument.setCreateTime(awemeCommentAddDto.getCreateTime());
        //增加回复数
        if(BusinessUtils.isRealId(awemeCommentAddDto.getReplyId())) {
            boolean incResult = awemeCommentService.inc(awemeCommentAddDto.getReplyId(), AwemeCommentDocument.field_replies, AwemeCommentDocument.class);
            //增加回复数失败 replyId异常
            if(!incResult) {
                log.error("评论回复异常！replyId = {}", awemeCommentAddDto.getReplyId());
                throw new BusinessException(BusinessException.MESSAGE_DATA_NOT_FOUND);
            }
            awemeCommentDocument.setReplyId(awemeCommentAddDto.getReplyId());
            if(BusinessUtils.isRealId(awemeCommentAddDto.getReplyToReplyId())) {
                AwemeCommentDocument replyToReplyComment = awemeCommentService.getById(awemeCommentAddDto.getReplyToReplyId(), AwemeCommentDocument.class);
                awemeCommentDocument.setReplyToReplyId(replyToReplyComment.getId());
                awemeCommentDocument.setReplyToUserId(replyToReplyComment.getUserId());
            }
        }
        awemeCommentService.insert(awemeCommentDocument);
    }
}
